﻿using System;
using System.IO;
using System.Net;
using System.Windows.Input;
using Marc.JwOrgClient.Util;

namespace Marc.JwOrgClient.ViewModels {
    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.Command;
    using Marc.JwOrgClient.Model;

    public class ChapterViewModel : ViewModelBase {
        public event EventHandler DownloadCompleted;
        private readonly PodcastMagazineChapter _chapter;
        private string _localPath;
        private IPodcastNamingStrategy _namingStrategy;
        private readonly ICommand _downloadCommand;

        private bool _isDownloaded;
        private bool _isDownloading;
        private string _directoryPath;
        private string _fileName;

        public ChapterViewModel(string rootPath, IPodcastNamingStrategy namingStrategy, PodcastMagazineChapter chapter) {
            _chapter = chapter;
            _downloadCommand = new RelayCommand(Download, () => !IsDownloading);
            ChangeNamingStrategy(rootPath, namingStrategy);
        }

        public void Download() {
            IsDownloading = true;
            if (!Directory.Exists(_directoryPath)) {
                Directory.CreateDirectory(_directoryPath);
            }

            if (IsDownloaded) {
                File.Delete(_localPath);
            }

            File.WriteAllBytes(_localPath, new WebClient().DownloadData(Chapter.Link));

            IsDownloading = false;
            IsDownloaded = true;
            if (DownloadCompleted != null) {
                DownloadCompleted(this, EventArgs.Empty);
            }
        }

        public bool IsDownloaded {
            get { return _isDownloaded; }
            set {
                if (value != _isDownloaded) {
                    _isDownloaded = value;
                    RaisePropertyChanged(() => IsDownloaded);
                }
            }
        }

        public bool IsDownloading {
            get { return _isDownloading; }
            set {
                if (value != _isDownloading) {
                    _isDownloading = value;
                    RaisePropertyChanged(() => IsDownloading);
                }
            }
        }

        public ICommand DownloadCommand {
            get { return _downloadCommand; }
        }

        public PodcastMagazineChapter Chapter {
            get { return _chapter; }
        }

        public void ChangeNamingStrategy(string rootPath, IPodcastNamingStrategy selectedNamingStrategy) {
            _namingStrategy = selectedNamingStrategy;
            _directoryPath = _namingStrategy.GetDirectoryPath(rootPath, Chapter.Magazine);
            _fileName = _namingStrategy.GetFileName(Chapter.Magazine, Chapter);
            _localPath = Path.Combine(_directoryPath, _fileName);
            IsDownloaded = File.Exists(_localPath);
        }
    }
}